package org.wishwork.api.product.category;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 商品类目查询
 * @author: WangYX
 * @create: 2022-04-08 17:10
 * @Version: 1.0.0
 **/
public class CategoryQueryApi extends Api<List<CategoryQueryResponse>, CategoryQueryRequest> {

    private static final Logger log = LoggerFactory.getLogger(CategoryQueryApi.class);

    private Context context;

    public CategoryQueryApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(CategoryQueryRequest categoryRequest) throws Exception {
        String url = "/open/category/query";
        Map<String, Object> params = new HashMap<>();
        if (categoryRequest.getCIds() != null && categoryRequest.getCIds().size() > 0) {
            params.put("c_ids", categoryRequest.getCIds());
        }
        if (categoryRequest.getParentCIds() != null && categoryRequest.getParentCIds().size() > 0) {
            params.put("parent_c_ids", categoryRequest.getParentCIds());
        }
        return HttpHelper.sendRequest(categoryRequest, params, url);
    }

    @Override
    protected List<CategoryQueryResponse> process(JSONObject data, CategoryQueryRequest categoryRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<CategoryQueryResponse> categoryQueryResponses = datas.toJavaList(CategoryQueryResponse.class);
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer pageIndex = categoryRequest.getPageIndex();
            CategoryQueryRequest build = categoryRequest.toBuilder().pageIndex(++pageIndex).build();
            List<CategoryQueryResponse> business = business(build);
            categoryQueryResponses.addAll(business);
        }
        return categoryQueryResponses;
    }
}
